<template>
  <div>
    <div >
      <div class="userImg"><img src="../../assets/icons/loginLogo.png" alt="" width="100%"></div>
      <mt-field class='mgtop10 after' :state="state.username" v-model="data.username" :attr="{ 'maxlength': 20 }" label="手机号"></mt-field>
      <mt-field class='after' label="密码" :attr="{ 'maxlength': 20 }" :state="state.password" v-model="data.password" :type="mytype" >
        <mt-switch v-model="switchValue"></mt-switch>
      </mt-field>
      <mt-field class='after' :attr="{'maxlength': 4 }" :state="state.verifyCode" v-model="data.verifyCode" label="验证码">
        <img  height="45px" width="100px" src='/free/authImage'  onclick="javascript:this.src='/free/authImage?date=' + new Date().getTime()" />
      </mt-field>
    </div>
    <div class="padlr10">
      <mt-button size="large" type="primary" @click="login()">登录</mt-button>
    </div>
    <div class="padlr10 clear">
      <router-link class='left' to="/login/register">注册</router-link>
      <router-link class='right' to="/login/modifyPassword">重置密码</router-link>
    </div>
  </div>
</template>

<script>
  import { Toast } from 'mint-ui';
  let attrs = [{name:'username',reg:/^1[23456789]\d{9}$/},
    {name:'password',reg:/.{6,}/},
    {name:'verifyCode',reg:/.{4}/}];
  export default {
    name: "login",
    data() {
      return {
        switchValue: true
        ,authImage:""
        ,data:{}
        ,state:{username:'',password:'',verifyCode:''}
      }
    },
    computed: {
      //计算属性
      mytype: function () {
        return this.switchValue ? 'password' : ''
      }
    },
    watch:{data:{
        handler(newVal,oldVal){
          attrs.forEach(n=>{
            if(newVal[n.name]==undefined||newVal[n.name]==''){
              this.state[n.name] = "";
            }else{
              this.state[n.name] = n.reg.test(newVal[n.name])?'success':'error';
            }
          })
        },
        deep:true
      }
    },
    methods:{
      login:function(){
        let vm = this;
        let attr = attrs.find(n=>{return vm.state[n.name]!='success'})
        if(attr){
           Toast(attr.name+"输入错误!");
           return;
        }
        this.$http.post("/wx/login",changeDataType(this.data)).then((resp)=>{
           if(resp.code == 0){
             Object.assign(vm.$root.userInfo,resp.data.userInfo);
             resp.data.allDict.forEach(dict=>vm.$root[dict.type]=eval(dict.jsonStr));
             vm.$router.push({path:"/UserCenter"})
           }else{
             Toast(resp.msg);
           }
        })
      }
    }
  }
</script>

<style scoped>
   .userImg{
      width: 90%;
      margin: 50px auto;
   }
</style>
